<?php

namespace app\api\controller;

use app\common\model\User;
use app\common\service\TokenService;
use Exception;
use think\Controller;
use think\exception\HttpResponseException;
use think\facade\Log;
use think\facade\Response;

class BaseApiController extends Controller
{
    protected $user = null;
    protected $is_auth = true;

    protected function initialize()
    {
        if ($this->is_auth) {
            try {
                $this->user = TokenService::auth(new User());
            } catch (Exception $e) {
                Log::error($e->getMessage());
                $this->errorReturn(null, 'token无效', 0, 401);
            }
        }
    }

    protected function successReturn($data = '', $msg = 'SUCCESS', $code = 1, $http_code = 200, array $header = [])
    {
        $result = [
            'code' => $code,
            'msg' => $msg,
            'data' => $data,
        ];
        $response = Response::create($result, 'json', $http_code)->header($header);
        throw new HttpResponseException($response);
    }

    protected function errorReturn($data = '', $msg = 'ERROR', $code = 0, $http_code = 200, array $header = [])
    {
        $result = [
            'code' => $code,
            'msg' => $msg,
            'data' => $data,
        ];
        $response = Response::create($result, 'json', $http_code)->header($header);
        throw new HttpResponseException($response);
    }

}